package com.renker.blog.manage.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;

import com.renker.blog.common.utils.AjaxUtil;
import com.renker.blog.common.utils.LoggerUtil;

@ControllerAdvice
public class ExceptionHandlerController {
	
	public final static String DEFAULT_EXCEPTION_ATTRIBUTE="shiro_exception";

	/**
	 * shiro UnauthorizedException 异常处理
	 */
	@ExceptionHandler(UnauthorizedException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public ModelAndView processUnauthenticatedException(HttpServletRequest request,UnauthorizedException e){
		
		LoggerUtil.debug("URI:"+request.getRequestURI()+"\t Method:"+request.getMethod()+"\t X-Requested-With="+request.getHeader("X-Requested-With")+"\t isAjax:"+AjaxUtil.isAjax(request));
		
		ModelAndView mv = new ModelAndView();
		mv.addObject("errorMsg", e.getMessage());
		mv.addObject(DEFAULT_EXCEPTION_ATTRIBUTE,e);
		if(!AjaxUtil.isAjax(request)){
			mv.setViewName("forward:/manage/unauthorized");
		}else{
			mv.setViewName("forward:/manage/unauthorizedAjax");
		}
		
		return mv;
		
	}
}
